package cn.sys.controller;

import cn.sys.controller.dto.MaintainDormitorySearchDTO;
import cn.sys.controller.dto.SearchDTO;
import cn.sys.entity.Student;
import cn.sys.service.MaintainDormitoryService;
import cn.sys.service.impl.MaintainDormitoryServiceImpl;
import cn.sys.util.FileUploadUtil;
import cn.sys.util.ResponseUtil;
import cn.sys.util.ResultData;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 报修管理
 */
@WebServlet("/maintainDormitory")
public class MaintainDormitoryServlet extends HttpServlet {
    private MaintainDormitoryService maintainDormitoryService = new MaintainDormitoryServiceImpl();
    @Override
    protected void service(HttpServletRequest req,
                           HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getParameter("action");
        System.out.println(action);

        switch (action){
            case "getMaintainDormitoryList":getMaintainDormitoryList(req, resp);break;
            case "addMaintainDormitory" :addMaintainDormitory(req, resp);break;
            case "dealMaintainDormitory" : dealMaintainDormitory(req, resp);break;
            case "handleMaintainDormitory" :handleMaintainDormitory(req, resp);break;

        }
    }

    // 修改报修状态
    private void handleMaintainDormitory(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Integer id = Integer.valueOf(req.getParameter("id"));
        Integer state = Integer.valueOf(req.getParameter("state"));
        // 注意获取到的state是当前未点击按钮时的状态，加一变为下一个状态
        ResultData resultData = maintainDormitoryService.updateMaintainDormitoryState(id, state+1);
        ResponseUtil.send(resp, resultData);
    }

    // 根据报修状态获取报修列表，需要获取报修信息和宿舍信息两个部分
    private void dealMaintainDormitory(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        /*
          三个功能，跳转同一个页面，通过传入的state值判断显示内容
          未处理报修管理、处理中报修管理、已处理报修管理
          获取三种状态的报修信息并加上其位置信息，存入集合中返回给页面渲染数据
         */
        // 1. 搜索条件、分页信息：日期范围，标题；分页信息（MaintainDormitorySearchDTO）
        // 2. 宿舍位置信息、报修信息（List<Map<String,Object>> -> 存入的是一个两表联合查询结果 ）
        MaintainDormitorySearchDTO searchDTO = new MaintainDormitorySearchDTO();
        searchDTO.setTitle(req.getParameter("title"));
        searchDTO.setState(Integer.valueOf(req.getParameter("state")));
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String startTime = req.getParameter("startTime");
        String endTime = req.getParameter("endTime");
        try {
            if (!(startTime == null || "".equals(startTime))) {
                searchDTO.setStartTime(format.parse(startTime));
            }
            if (!(endTime == null || "".equals(endTime))) {
                searchDTO.setEndTime(format.parse(endTime));
            }
        }catch (ParseException e){
            e.printStackTrace();
        }
        // valueOf转为Integer类型，parseInt转为int类型
        searchDTO.setPageNum(Integer.valueOf(req.getParameter("currPage")));
        searchDTO.setPageSize(Integer.valueOf(req.getParameter("pageSize")));
        ResultData resultData = maintainDormitoryService.getMaintainDormitoryListAndPositionByState(searchDTO);
        ResponseUtil.send(resp, resultData);
    }

    // 添加报修记录
    private void addMaintainDormitory(HttpServletRequest req, HttpServletResponse resp) throws IOException{
        // 获取登录的用户信息，等会插入数据到数据库中需要使用
        HttpSession session = req.getSession();
        Student student = (Student) session.getAttribute("studentInfo");
        if(student == null){
            ResponseUtil.send(resp, ResultData.fail(ResultData.OPERATION_FAIL, "请先登录"));
        }else {
            // 在session中获取用户id
            Integer stuId = student.getStuId();

            // 文件上传，指定上传位置，并获取到文件名组成的JSON数组
            String filePath = "D:\\MyStudy_22\\EducationBase\\JavaEE\\Work\\StudentSysManager\\web" + File.separator + "images";
            String imageUrls = FileUploadUtil.upload(req, "images", filePath);

            // 获取报修宿舍Id、标题和详细描述
            Integer dorId = Integer.valueOf(FileUploadUtil.getStringInfo(req, "dorId"));
            String title = FileUploadUtil.getStringInfo(req, "title");
            String desc = FileUploadUtil.getStringInfo(req, "desc");

            ResultData resultData = maintainDormitoryService.addMaintainDormitory(stuId, dorId, imageUrls, title, desc);
            ResponseUtil.send(resp, resultData);
        }
    }

    // 根据学生信息，获取报修信息列表
    private void getMaintainDormitoryList(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        MaintainDormitorySearchDTO searchDTO = new MaintainDormitorySearchDTO();
        ResultData resultData = null;
        try {
            HttpSession session = req.getSession();
            Student student = (Student) session.getAttribute("studentInfo");
            if(student == null){
                ResponseUtil.send(resp, ResultData.fail(ResultData.LOGIN_FAIL, "请先登录"));
                return;
            }
            searchDTO.setStuId(student.getStuId());
            searchDTO.setTitle(req.getParameter("title"));
            searchDTO.setState(Integer.valueOf(req.getParameter("state")));

            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            // 注意如果没有值会转换失败，所以需要先判断
            if (!(req.getParameter("startTime") == null || "".equals(req.getParameter("startTime")))) {
                searchDTO.setStartTime(format.parse(req.getParameter("startTime")));
            }
            if (!(req.getParameter("endTime") == null || "".equals(req.getParameter("endTime")))) {
                searchDTO.setEndTime(format.parse(req.getParameter("endTime")));
            }
            searchDTO.setPageNum(Integer.valueOf(req.getParameter("currPage")));
            searchDTO.setPageSize(Integer.valueOf(req.getParameter("pageSize")));

            resultData = maintainDormitoryService.getMaintainDormitoryList(searchDTO);

        } catch (ParseException e) {
            e.printStackTrace();
        }
        ResponseUtil.send(resp, resultData);
    }
}
